<?php

class RegistrationController extends Controller {

	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index', 'default', 'view', 'missing'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create', 'download', 'update', 'admin'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('delete'),
				'users'=>array('admin'),
			),
			array('deny', // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		$this->render('view', array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate() {
		$model = new Registration;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Registration'])) {
			$model->attributes = $_POST['Registration'];
			if ($model->save())
				$this->redirect(array('view', 'id'=>$model->_id));
		}

		$this->render('create', array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		$model = $this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Registration'])) {
			$model->attributes = $_POST['Registration'];
			if ($model->save())
				$this->redirect(array('view', 'id'=>$model->_id));
		}

		$this->render('update', array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('Registration');
		$this->render('index', array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new Registration('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Registration']))
			$model->attributes = $_GET['Registration'];

		$this->render('admin', array(
			'model'=>$model,
		));
	}

	public function actionDownload() {
		$model = new Registration('download');
		if (isset($_POST['Registration'])) {
			$model->attributes = $_POST['Registration'];
			if ($model->validate()) {
				$this->_download($model->beginDate, $model->endDate);
			}
		} else {
			$now = date('Y-m-d');
			$model->beginDate = $now;
			$model->endDate = $now;
		}
		$this->render('download', array('model'=>$model));
	}

	private function _createExcel($rows) {
		$phpExcelPath = Yii::getPathOfAlias('application.components');
		spl_autoload_unregister(array('YiiBase', 'autoload'));
		include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
		$excel = new PHPExcel();
		$excel->getProperties()->setCreator("Ayamo")
			->setLastModifiedBy("Ayamo")
			->setTitle("Senkom Information Center Report")
			->setSubject("Report")
			->setDescription("Senkom Information Center Report")
			->setKeywords("senkom report")
			->setCategory("Daily Report");
		$sheet = $excel->setActiveSheetIndex(0);
		$sheet->setCellValue("A1", "Laporan Harian Senkom Information Center");
		$sheet->setCellValue("A4", "ID");
		$sheet->setCellValue("B4", "Nama");
		$sheet->setCellValue("C4", "Tempat Lahir");
		$sheet->setCellValue("D4", "Tanggal Lahir");
		$sheet->setCellValue("E4", "Email");
		$sheet->setCellValue("F4", "Telepon");
		$sheet->setCellValue("G4", "Jabatan");
		$sheet->setCellValue("H4", "Alamat");
		$sheet->setCellValue("I4", "Kota/Kab");
		$sheet->setCellValue("J4", "Kota/Kab");
		$sheet->setCellValue("K4", "Propinsi");
		$sheet->setCellValue("L4", "Utusan");
		$sheet->setCellValue("M4", "Utusan Propinsi");
		$sheet->setCellValue("N4", "Utusan Kota/Kab");
		$formatDate = 'D MMMM YYYY';
		foreach ($rows as $key=>$row) {
			$index = $key + 5;
			$sheet->setCellValue("A$index", $row->_id);
			$sheet->setCellValue("B$index", $row->name);
			$sheet->setCellValue("C$index", $row->birthPlace);
			$date = strtotime($row->birthDate);
			$date = PHPExcel_Shared_Date::PHPToExcel($date + (60 * 60 * 7));
			$sheet->setCellValue("D$index", $date);
			$sheet->getStyle("D$index")->getNumberFormat()
				->setFormatCode($formatDate);
			$sheet->setCellValue("E$index", $row->emails);
			$sheet->setCellValue("F$index", $row->phones);
			$sheet->setCellValue("G$index", $row->position);
			$sheet->setCellValue("H$index", $row->homeAddress);
			$sheet->setCellValue("I$index", $row->homeCityType);
			$sheet->setCellValue("J$index", $row->homeCity);
			$sheet->setCellValue("K$index", $row->province);
			$sheet->setCellValue("L$index", $row->envoy);
			$sheet->setCellValue("M$index", $row->envoyProvince);
			if ($row->envoy != Registration::ENVOY_PROVINCE) {
				$sheet->setCellValue("N$index", $row->envoyCity);
			}
		}
		$excel->getActiveSheet()->setTitle('Peserta Munas');
		$excel->setActiveSheetIndex(0);
		$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
		$folder = Yii::app()->params['file'] . '/registration';
		$objWriter->save("$folder/munas.xls");
		spl_autoload_register(array('YiiBase', 'autoload'));
	}

	private function _createZip($rows) {
		$folder = Yii::app()->params['file'] . '/registration';
		$zip = new ZipArchive();
		$zip->open("$folder/munas.zip", ZipArchive::OVERWRITE);
		$zip->addFile("$folder/munas.xls", 'Peserta.xls');
		foreach ($rows as $row) {
			$name = "{$row->_id}.{$row->extension}";
			$alias = "{$row->_id} - {$row->name}.{$row->extension}";
			$zip->addFile("$folder/$name", $alias);
		}
		$zip->close();
	}

	private function _download($beginDate, $endDate) {
		$begin = strtotime("$beginDate 00:00:00");
		$end = strtotime("$endDate 23:59:59");
		$criteria = new CDbCriteria();
		$criteria->condition = 'updateTime >= :begin AND updateTime <= :end';
		$criteria->params = array(':begin'=>$begin, ':end'=>$end);
		$rows = Registration::model()->findAll($criteria);
		if (count($rows) == 0)
			return;

		$this->_createExcel($rows);
		$this->_createZip($rows);
		$app = Yii::app();
		$folder = $app->params['file'] . '/registration';
		$app->request->xSendFile(realpath("$folder/munas.zip"));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = Registration::model()->findByPk($id);
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'registration-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	public function actionDefault() {
		$this->render('default');
	}

	public function actionMissing() {
		$cmd = Yii::app()->db->createCommand();
		$cmd->from('province p');
		$cmd->select('p.name');
		$cmd->order('p.name');
		$cmd->leftJoin(
			'registration r', 'p.name=r.envoyProvince'
		);
		$cmd->where('r._id is null');
		$provinces = $cmd->query();
		
		$cmd = Yii::app()->db->createCommand();
		$cmd->from('city c');
		$cmd->select('c.name, c.type');
		$cmd->order('c.name, c.type');
		$cmd->leftJoin(
			'registration r', 'c.type=r.envoy AND c.name=r.envoyCity'
		);
		$cmd->where('r._id is null');
		$cities = $cmd->query();
		
		$data = array('provinces'=>$provinces, 'cities'=>$cities);
		$this->render('missing', $data);
	}

}
